package idv.arthur.work;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QueryHost extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QueryHost() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		
		String strSQL = "";
		ResultTableSet resultTableSet = new ResultTableSet();
		String fromCall = request.getParameter("fc");
		ArrayList<InfoStruc> infoStrucs = new ArrayList<InfoStruc>();
		int page = Integer.parseInt(request.getParameter("page"));
		int total_pages = 1;
		int count  = 0;
		int limit = Integer.parseInt(request.getParameter("rows"));
		String sord = request.getParameter("sord");
		String sidx =  request.getParameter("sidx");
		
		if ("".equalsIgnoreCase(sidx) || "my_checkbox".equalsIgnoreCase(sidx)) {
			sidx = "hostName";
		} else if ("hostIP".equalsIgnoreCase(sidx)) {
			sidx = "ip";	//因為UI和Shema的名稱不一樣
		}
		
		try {
			conn = wid.getConn(true);	
			
			if ("host".equalsIgnoreCase(fromCall)||"mappingSquadHost".equalsIgnoreCase(fromCall)) {
				strSQL = "SELECT COUNT(*) FROM hosts WHERE bssid=? AND subsysid=?";
			} else {
				strSQL = "SELECT COUNT(*) FROM hosts";
			}
			
			ps = conn.prepareStatement(strSQL);
			if ("host".equalsIgnoreCase(fromCall)||"mappingSquadHost".equalsIgnoreCase(fromCall)) {
				ps.setString(1, request.getParameter("bssId"));
				ps.setString(2, request.getParameter("subSysId"));	
			}
			rs = ps.executeQuery();
			rs.next();
			count  = rs.getInt(1);
			
			if ( count  != 0 ) {
				
				if (limit  < count) {
					total_pages = (count / limit)+1;	
				}
				if ( conn.getMetaData().getDatabaseProductName().contains( "MySQL" ) ) {
					if ("mappingSquadHost".equalsIgnoreCase(fromCall)) {
						strSQL = "SELECT mpsquadhosts.bssid as 'i',hosts.ip,hosts.port,hosts.hostname,hosts.bssid,hosts.subsysid FROM hosts LEFT JOIN mpsquadhosts ON hosts.bssid=mpsquadhosts.bssid AND hosts.subsysid=mpsquadhosts.subsysid AND hosts.ip=mpsquadhosts.ip AND hosts.port=mpsquadhosts.port AND mpsquadhosts.envid=?  AND mpsquadhosts.squadid=? WHERE hosts.bssid=? AND hosts.subsysid=? ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;
					} else if ("host".equalsIgnoreCase(fromCall)) {
						strSQL = "SELECT t1.ip, t1.subsysid, t1.bssid, t1.port, t1.hostname,t1.loginId,t1.loginPWD,t2.bssname,t3.subsysname FROM hosts t1,bss t2,subsys t3 WHERE t1.bssid = t2.bssid AND t1.subsysid = t3.subsysid AND t1.bssid=? AND t1.subsysid=? ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;
					} else {
						strSQL = "SELECT t1.ip, t1.subsysid, t1.bssid, t1.port, t1.hostname,t1.loginId,t1.loginPWD,t2.bssname,t3.subsysname FROM hosts t1,bss t2,subsys t3 WHERE t1.bssid = t2.bssid AND t1.subsysid = t3.subsysid ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;	
					}	
				} else if ( conn.getMetaData().getDatabaseProductName().contains( "Informix" ) ) {
					if ("mappingSquadHost".equalsIgnoreCase(fromCall)) {
						strSQL = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +" t2.bssid as i,t1.ip,t1.port,t1.hostname,t1.bssid,t1.subsysid FROM hosts t1,OUTER mpsquadhosts t2 WHERE t1.bssid=t2.bssid AND t1.subsysid=t2.subsysid AND t1.ip=t2.ip AND t1.port=t2.port AND t2.envid=?  AND t2.squadid=? AND t1.bssid=? AND t1.subsysid=?  ORDER BY "+sidx+" "+sord;
					} else if ("host".equalsIgnoreCase(fromCall)) {
						strSQL = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +"  t1.ip, t1.subsysid, t1.bssid, t1.port, t1.hostname,t1.loginId,t1.loginPWD,t2.bssname,t3.subsysname FROM hosts t1,bss t2,subsys t3 WHERE t1.bssid = t2.bssid AND t1.subsysid = t3.subsysid AND t1.bssid=? AND t1.subsysid=? ORDER BY "+sidx+" "+sord;
					} else {
						strSQL = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +" t1.ip, t1.subsysid, t1.bssid, t1.port, t1.hostname,t1.loginId,t1.loginPWD,t2.bssname,t3.subsysname FROM hosts t1,bss t2,subsys t3 WHERE t1.bssid = t2.bssid AND t1.subsysid = t3.subsysid ORDER BY "+sidx+" "+sord;
					}
				}
				
				
				ps = conn.prepareStatement(strSQL);
				if ("mappingSquadHost".equalsIgnoreCase(fromCall)) {
					ps.setString(1, request.getParameter("envId"));
					ps.setString(2, request.getParameter("squadId"));
					ps.setString(3, request.getParameter("bssId"));
					ps.setString(4, request.getParameter("subSysId"));
				} else if ("host".equalsIgnoreCase(fromCall)) {
					ps.setString(1, request.getParameter("bssId"));
					ps.setString(2, request.getParameter("subSysId"));
				} 
				
				rs = ps.executeQuery();
				ArrayList<Rows> rows = new ArrayList<Rows>();
				
				while ( rs.next() ) {
					String hostIP = rs.getString("ip");
					if ("JSON".equalsIgnoreCase(fromCall)) {
						InfoStruc infoStruc = new InfoStruc();
						infoStruc.setId(hostIP);
						infoStruc.setName( wid.DB2UI( rs.getString("hostname"),conn.getMetaData().getDatabaseProductName() ) );
						infoStrucs.add(infoStruc);
					} else {
						Rows row = new Rows();
						String[] cell = null;
						row.setId(hostIP+wid.DB2UI( rs.getString("hostname"),conn.getMetaData().getDatabaseProductName() )+rs.getInt("port")+rs.getString("bssid")+rs.getString("subsysid"));
						if ("mappingSquadHost".equalsIgnoreCase(fromCall)) {
							cell = new String[6];
							cell[0] = rs.getString("i");
							cell[1] = hostIP;
							cell[2] = wid.DB2UI( rs.getString("hostname"),conn.getMetaData().getDatabaseProductName() );
							cell[3] = String.valueOf(rs.getInt("port"));
							cell[4] = rs.getString("bssid");
							cell[5] = rs.getString("subsysid");
						} else {
							cell = new String[5];
							cell[0] = hostIP;
							cell[1] = wid.DB2UI( rs.getString("hostname"),conn.getMetaData().getDatabaseProductName() );
							cell[2] = String.valueOf(rs.getInt("port"));
							cell[3] = rs.getString("loginId");
							cell[4] = rs.getString("loginPWD");
						}
						row.setCell(cell);
						rows.add(row);
						
					}
				}
				resultTableSet.setRows(rows);
				resultTableSet.setPage(String.valueOf(page));
				resultTableSet.setTotal(total_pages);
				resultTableSet.setRecords(String.valueOf(count));
				
			} else {
				page =0;
				total_pages=0;
				resultTableSet.setPage(String.valueOf(page));
				resultTableSet.setTotal(total_pages);
				resultTableSet.setRecords(String.valueOf(count));
			}
		} catch ( SQLException e) {
			wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch ( UnsupportedEncodingException e) {
			wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch ( Exception e) {
			wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}
		
		if ("JSON".equalsIgnoreCase(fromCall)) {
			response.getWriter().write(new Gson().toJson(infoStrucs));
		} else {
			response.getWriter().write(new Gson().toJson(resultTableSet));	
		}
	}
}